import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch, Link, } from "react-router-dom";
import { ImagePicker, WingBlank, Toast } from "antd-mobile";
import { Form, Icon, Input, Button, Alert, Layout, Avatar, Modal, message, Select, Upload, Card, Row, Col, Radio, Image } from "antd";
import { PoweroffOutlined, SoundTwoTone } from '@ant-design/icons';
import { getSendVideoEventMessageForIdApi } from "../js/patrolpushapi.js";
import {
    updateSafetySceneStatusAndContent, updateSafetySceneStatusApi, insertSafetySceneDealApi,
    getSafetySceneStatusApi, getWechatGetOpenIdApi, getRealNameByWechatIdApi, getSafetySceneDealInfoApi
} from "../js/eventpush.js";

import { getSignature } from "../js/dangerpushapi.js";
import { iconFontUrl } from "../js/config.js";

const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl
});

const FormItem = Form.Item;

import { AntDesignOutlined } from '@ant-design/icons';
const { Meta } = Card;

const WX = require("jweixin-wechat");

class EventPush extends Component {

    constructor(props) {
        super(props);
        this.state = {
            nodata: false,
            data: [],
            isDeal: true,
            isDeal2: false,
            isButton: false,
            isButton2: false,
            realname: "xxx",
            dealTime: "xxxx-xx-xx xx:xx:xx",
            dealContent: "无",
            openId:"",
            dealUser:11501
            
        };
    }

    previewImageDeal() {
        WX.previewImage({
            current: this.state.data.image, // 当前显示图片的http链接
            urls: [this.state.data.image] // 需要预览的图片http链接列表
        })
    }
    componentDidMount() {
        getSignature(window.location.href)
            .then(res => {
                WX.config({
                    debug: false, //开启debug模式，在验证签名过程中会返回对应信息
                    appId: res.data.appid,
                    signature: res.data.signature,
                    nonceStr: res.data.noncestr,
                    timestamp: res.data.timestamp,
                    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']// 必填，需要使用的JS接口列表
                });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        let urlData = this.getUrlParam("state");
        let id = urlData.split("=")[1].replace("#", '');
        console.log('urlData', urlData.split("="), id);
        // message.error(code, 10)
        // let id = 202016
        if (id == 0 || id == undefined || id == null) {
            this.setState({
                isDeal: false
            })
        }
        WX.ready(function () {
            var obj = {
                title: "平台报警通知", // 分享标题
                desc: '点击查看平台报警事件' + '详情！', // 分享描述
                link: 'https://tidukeji.cn/dailypush/eventpush/index.html?state=' + parseInt(id), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                // 该链接是重定向链接，因为需要获取用户code，但是该链接又无法直接写微信获取code的链接，
                // 所以需要点击后重新加载新的页面，来实现重定向，重新打开获取code的微信链接，实现获取用户信息的功能；
                imgUrl: 'https://tidukeji.cn/wxImage/newLogo.png', // 分享图标
                fail: function (res) {
                    console.log(JSON.stringify(res));
                }
            };
            // 2.1 监听“分享给朋友”，按钮点击、自定义分享内容及分享结果接口
            WX.onMenuShareAppMessage(obj);

            // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
            WX.onMenuShareTimeline(obj);
        })


        getSendVideoEventMessageForIdApi(id)
            .then((res) => {
                console.log("res.data:", res.data)
                this.setState({
                    data: res.data
                })
                let schoolId = res.data.schoolId
                let image = res.data.image
                let imageUrl = "/image/eventimage/" + image.split("/")[5]
                let time = res.data.time
                getSafetySceneStatusApi(parseInt(schoolId), imageUrl, time)
                    .then((res) => {
                        console.log("res.data2:", res.data)
                        if (res.data.status == 5) {
                            this.setState({
                                isButton: true
                            })
                            getSafetySceneDealInfoApi(parseInt(res.data.safetySceneId))
                                .then((res) => {
                                    console.log(res.data)
                                    this.setState({
                                        realname: res.data.realname,
                                        dealTime: res.data.createTime,
                                        dealContent: res.data.dealContent,
                                        isDeal2: true
                                    })
                                })
                        } else if (res.data.status == 6) {
                            this.setState({
                                isButton: false
                            })
                        } else if (res.data.status == 7) {
                            this.setState({
                                isButton: false,
                                isButton2: true
                            })
                        } else {
                            this.setState({
                                isDeal: false
                            })
                        }

                    })
                switch (res.data.eventTypeName) {
                    case " ":
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });

        //获取微信号
        let code = this.getUrlParam2("code");
        getWechatGetOpenIdApi(code).then((res) => {
            console.log("微信号", res.data)
            this.setState({
                openId: res.data.openId
            })
            getRealNameByWechatIdApi(parseInt(4), res.data.openId).then((res) => {
                if (res.data.status == "success") {
                    this.setState({
                        dealUser: res.data.dealUser
                    })
                }
            })
        })


    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=[0-9]*(#|$)"); //构造一个含有目标参数的正则表达式对象
        // //本地测试
        // var l="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa3c085447f9faefa&redirect_uri=https%3a%2f%2ftidukeji.cn%2fdailypush%2feventpush%2findex.html&response_type=code&scope=snsapi_base&state=9509#wechat_redirect"
        // var r =l.substr(1).match(reg);  //匹配目标参数
        //线上
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        console.log('wos', r);
        if (r != null) return unescape(r[0]);
        return null; //返回参数值
    }

    getUrlParam2(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }


    render() {
        const bindImageSrc = this.state.data.image || 'http://47.111.158.147:8080/fileImage/123002_1607328079415.jpg';
        //const bindImageSrc = 'http://47.111.158.147:8080/fileImage/123002_1607328079415.jpg';
        return (
            <div style={{

                width: '100%',

                height: '100%',
                backgroundColor: '#ffffff',
                // marginLeft:'10%'
                padding: '-5px',
            }}>
                {
                    this.state.nodata ? (<IconFont type="icon-zanwushuju" style={{
                        position: 'fixed',
                        fontSize: '180px',
                        left: '50%',
                        top: '50%',
                        transform: 'translate(-50%, -50%)'

                    }} />) : (

                        <div style={{

                            width: '100%',
                            margin: '0 auto',
                            // height: '100%',
                            overflow: 'hidden',

                        }}>

                            <Card
                                title={<Meta
                                    avatar={<Avatar src="https://tidukeji.cn/wxImage/newLogo.png" />}
                                    title={this.state.data.eventTypeName ? this.state.data.eventTypeName : '陌生人识别事件'}
                                    //title={this.state.data.eventTypeName='危险行为识别事件'}
                                    description="平台报警通知"
                                />} bordered={false}>

                                {
                                    !this.state.isDeal2 ? <EventTempleate type={this.state.data.eventTypeName ? this.state.data.eventTypeName : '陌生人识别事件'} eventData={this.state.data} />
                                        : <EventTempleate3 realname={this.state.realname} dealTime={this.state.dealTime} dealContent={this.state.dealContent} />
                                }

                                <div style={{ height: '80%', overflow: 'hidden', fontSize: "1rem", textAlign: 'center', }} onClick={() => this.previewImageDeal()}>


                                    <img style={{

                                        width: 250,
                                        height: 250,

                                        textAlign: 'center',
                                        border: '1px dashed #d9d9d9',
                                        borderRadius: '4px',
                                    }} src={bindImageSrc} />

                                    <p style={{ marginBottom: '10px', marginTop: '10px', color: '#333333' }}>现场照片</p>

                                </div>
                                {
                                    this.state.isDeal ?
                                        <div style={{ marginTop: '40px', textAlign: 'center' }}>
                                            {
                                                !this.state.isButton ?
                                                    <Button type="primary" size='large' disabled={false} style={{ width: '90%', height: '40px' }}>
                                                        {
                                                            !this.state.isButton2 ?
                                                                <Link to={{
                                                                    pathname: '/eventpushdeal',
                                                                    state: {
                                                                        dealUser: this.state.dealUser,
                                                                        eventTypeName: this.state.data.eventTypeName,
                                                                        eventData: this.state.data
                                                                    }
                                                                }}
                                                                    style={{ margin: 'auto', fontSize: '1rem' }}>
                                                                    <div>去处理</div>
                                                                </Link> :
                                                                <Link to={{
                                                                    pathname: '/eventpushdeal',
                                                                    state: {
                                                                        dealUser: this.state.dealUser,
                                                                        eventTypeName: this.state.data.eventTypeName,
                                                                        eventData: this.state.data
                                                                    }
                                                                }}
                                                                    style={{ margin: 'auto', fontSize: '1rem' }}>
                                                                    <div>正在处理...</div>
                                                                </Link>
                                                        }
                                                    </Button>
                                                    :
                                                    <Button type="primary" size='large' disabled={true} style={{ width: '90%', height: '40px' }}>
                                                        <div>已处理</div>
                                                    </Button>
                                            }
                                        </div>
                                        : null
                                }
                            </Card>
                        </div>

                    )

                }
            </div>


        )

    }



}

function EventTempleate(props) {

    let eventData = props.eventData

    // console.log(props.type);
    const colors = "studentinoutpush1"
    switch (props.type) {

        case '重点人员识别事件':
            //case '危险行为识别事件':
            return (

                <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>您好！平台发现重点监控人员
                    <span className={colors}> {eventData.blackName ? eventData.blackName : "未知人员"}  </span>于 <span className={colors}>{eventData.time} </span> 时出现在
                    <span className={colors}>  {eventData.deviceAddress}  </span> ，请安保人员留意，尽快处置。

                </p>)
        // <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>您好！平台于<span className={colors}>2020-08-17 08:39:17</span>时在
        //     <span className={colors}> {eventData.deviceAddress}  </span>地点发现疑似<span className={colors}>斗殴</span>危险动作，请安保人员留意，尽快处置。

        // </p>)
        case '区域入侵事件':

            return (

                <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>您好！平台于 <span className={colors}>{eventData.time} </span>发现有人员在非正常时段进入
                    <span className={colors}>  {eventData.deviceAddress}报警区域，  </span> 请安保人员留意，尽快处置。

                </p>)
        case '陌生人识别事件':

            return (

                <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>您好！平台发现有陌生人员于 <span className={colors}>{eventData.time} </span> 时进入
                    <span className={colors}>  {eventData.deviceAddress}  </span> ，请安保人员留意，尽快处置。

                </p>)
        default: {
            return (

                <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>您好！平台发现有陌生人于 <span className={colors}>{eventData.time} </span> 时进入
                    <span className={colors}>  {eventData.deviceAddress}  </span> ，请安保人员留意，尽快处置。

                </p>)
        }
    }
}

function EventTempleate2(props) {

    let eventData = props.eventData

    // console.log(props.type);
    const colors = "studentinoutpush1"
    switch (props.type) {

        case '重点人员识别事件':
            //case '危险行为识别事件':
            return (

                <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>重点监控人员
                    <span className={colors}> {eventData.blackName ? eventData.blackName : "未知人员"}  </span>于 <span className={colors}>{eventData.time} </span> 时出现在
                    <span className={colors}>  {eventData.deviceAddress}  </span>

                </p>)
        // <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>您好！平台于<span className={colors}>2020-08-17 08:39:17</span>时在
        //     <span className={colors}> {eventData.deviceAddress}  </span>地点发现疑似<span className={colors}>斗殴</span>危险动作，请安保人员留意，尽快处置。

        // </p>)
        case '区域入侵事件':

            return (

                <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>在<span className={colors}>{eventData.time} </span>发现有人员在非正常时段进入
                    <span className={colors}>  {eventData.deviceAddress}报警区域</span>
                </p>)
        case '陌生人识别事件':
            return (

                <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>在<span className={colors}>{eventData.time} </span> 时进入
                    <span className={colors}>  {eventData.deviceAddress}  </span> ，请安保人员留意，尽快处置。

                </p>)
        default: {
            return (

                <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>在<span className={colors}>{eventData.time} </span> 时进入
                    <span className={colors}>  {eventData.deviceAddress}  </span>

                </p>)
        }
    }
}
function EventTempleate3(props) {
    let realname = props.realname
    let dealTime = props.dealTime
    let dealContent = props.dealContent
    const colors = "studentinoutpush1"
    return (
        <p style={{ textAlign: 'left', textIndent: '1em', fontSize: '1rem', letterSpacing: 1 }}>此事件在
            <span className={colors}> {dealTime}  </span> 已被 <span className={colors}>{realname} </span> 处理掉了。(备注信息: <span className={colors}>{dealContent} </span>)
        </p>
    )


}

//处理事件界面
class eventPushDeal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            eventData: this.props.location.state.eventData,
            buttonLoading: false,
            buttonLoading2: false,
            inputValue: "",
            dealUser: this.props.location.state.dealUser
        };
    }
    componentWillMount() {
        if (JSON.stringify(this.props.location.state.eventData) != undefined && JSON.stringify(this.props.location.state.eventData) != null 
        && JSON.stringify(this.props.location.state.dealUser) != null && JSON.stringify(this.props.location.state.eventData) != undefined) {
            this.setState({
                eventData: this.props.location.state.eventData,
                dealUser: this.props.location.state.dealUser
            })
        }
    }

    componentDidMount() {
    }



    previewImageDeal() {
        WX.previewImage({
            current: this.state.eventData.image, // 当前显示图片的http链接
            urls: [this.state.eventData.image] // 需要预览的图片http链接列表
        })
    }
    back = () => {
        window.history.back();
        this.setState({
            buttonLoading: false,
            buttonLoading2: false
        })
    }
    searchSubmit = (e) => {
        e.preventDefault();
        let eventData = this.state.eventData;
        let schoolId = eventData.schoolId
        let image = eventData.image
        let imageUrl = "/image/eventimage/" + image.split("/")[5]
        let time = eventData.time
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (values.dealview == undefined || values.dealview == "") {
                    message.error('请填写完整！');
                } else {
                    this.setState({
                        buttonLoading: true
                    })
                    updateSafetySceneStatusApi(parseInt(schoolId), imageUrl, time)
                        .then((res) => {
                            if (res.data.safesceneId != 0) {
                                insertSafetySceneDealApi(parseInt(res.data.safetySceneId), values.dealview)
                                    .then((res) => {
                                        if (res.data == "success") {
                                            message.success('提交成功');
                                            this.back();
                                        }

                                    })
                            } else {
                                message.error('提交失败，请重试');
                            }
                        })
                }
            }
        });
    }

    submitDealing = () => {
        console.log("正在处理。。。")
        let eventData = this.state.eventData;
        let schoolId = eventData.schoolId
        let image = eventData.image
        let imageUrl = "/image/eventimage/" + image.split("/")[5]
        let time = eventData.time
        this.setState({
            buttonLoading2: true
        })
        if (this.state.inputValue == "") {
            updateSafetySceneStatusAndContent(parseInt(schoolId), imageUrl, time, parseInt(7))
                .then((res) => {
                    console.log(res.data)
                    if (res.data.msg == "success") {
                        message.success('提交成功！');
                        this.back();
                    } else {
                        message.error('提交失败！');
                        this.setState({
                            buttonLoading2: false
                        })
                    }
                })
        } else {
            updateSafetySceneStatusAndContent(parseInt(schoolId), imageUrl, time, parseInt(7), this.state.inputValue)
                .then((res) => {
                    console.log(res.data)
                    if (res.data.msg == "success") {
                        message.success('提交成功！');
                        this.back();
                    } else {
                        message.error('提交失败！');
                        this.setState({
                            buttonLoading2: false
                        })
                    }
                })
        }

    }

    submitDealed = () => {
        console.log("已处理。。。")
        let eventData = this.state.eventData;
        let schoolId = eventData.schoolId
        let image = eventData.image
        let imageUrl = "/image/eventimage/" + image.split("/")[5]
        let time = eventData.time
        this.setState({
            buttonLoading: true
        })
        updateSafetySceneStatusApi(parseInt(schoolId), imageUrl, time, parseInt(5))
            .then((res) => {
                if (res.data.safesceneId != 0) {
                    insertSafetySceneDealApi(parseInt(res.data.safetySceneId), this.state.inputValue, this.state.dealUser)
                        .then((res) => {
                            if (res.data == "success") {
                                message.success('提交成功！');
                                this.back();
                            }
                        })
                } else {
                    message.error('提交失败!');
                    this.setState({
                        buttonLoading: false
                    })
                }
            })
    }

    setInputValue = (event) => {
        this.setState({
            inputValue: event.target.value
        })
    }

    render() {
        let eventData = this.state.eventData
        let eventTypeName = eventData.eventTypeName
        const bindImageSrc = eventData.image || 'http://47.111.158.147:8080/fileImage/123002_1607328079415.jpg';
        const { getFieldDecorator, getFieldValue } = this.props.form;
        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };
        return (
            <div style={{
                width: '100%',
                height: '100%',
                backgroundColor: '#ffffff',
                // marginLeft:'10%'
                overflow: 'auto',
                padding: '-5px',
            }}>
                <Card
                    title={<Meta
                        avatar={<Avatar src="https://tidukeji.cn/wxImage/newLogo.png" />}
                        title={eventTypeName}
                        description="平台报警处理"
                    />} bordered={false}>

                    <EventTempleate2 type={eventTypeName} eventData={this.state.eventData} />

                    <div style={{ height: '80%', overflow: 'hidden', fontSize: "1rem", textAlign: 'center', }} onClick={() => this.previewImageDeal()}>
                        <img style={{
                            width: 250,
                            height: 250,
                            textAlign: 'center',
                            border: '1px dashed #d9d9d9',
                            borderRadius: '4px',
                        }} src={bindImageSrc} />
                    </div>
                </Card>
                <div style={{ marginTop: 0, width: '100%', textAlign: 'center' }}>
                    {/* <Form style={{
                        width: '100%',
                        textAlign: 'center',
                        padding: '12px',
                        backgroundColor: '#ffffff',
                        borderRadius: 8,
                        marginBottom: 10,
                    }}> */}
                    <div style={{ marginLeft: '10%', marginBottom: '5px', fontSize: '0.8rem', textAlign: 'left' }}>
                        *备注信息(根据实际情况进行填写)
                    </div>
                    <div style={{ width: '80%', marginLeft: '10%', marginRight: '20%', marginBottom: '20px' }}>
                        <Input.TextArea onChange={this.setInputValue} maxLength={100} autoSize={{ minRows: 2 }} allowClear />
                    </div>
                    <div style={{ marginBottom: '20px' }}>
                        <Button type="primary" loading={this.state.buttonLoading2} onClick={() => this.submitDealing()}
                            style={{ width: '80%', height: '40px', fontSize: '1rem' }}>正在处理</Button>
                    </div>
                    <div>
                        <Button type="primary" loading={this.state.buttonLoading} onClick={() => this.submitDealed()}
                            style={{ width: '80%', height: '40px', fontSize: '1rem' }}>已处理</Button>
                    </div>
                    {/* <FormItem
                            label="处理建议"
                            style={{ width: '80%', marginLeft:'10%', marginRight:'20%'}}>
                            {getFieldDecorator("dealview", {
                                rules: [{
                                    required: true,
                                    message: "处理意见不能为空！"
                                }]
                            })(
                                <Input.TextArea maxLength={100}  autoSize={{minRows: 3}} allowClear/>
                            )}
                        </FormItem> */}

                    {/* <FormItem
                            style={{ float: 'center' }}>
                            <Button type="primary"  loading={this.state.buttonLoading} onConClick={() => this.submitDealing()} 
                            style={{ width: '80%', height:'40px', fontSize:'1rem'}}>正在处理</Button>
                        </FormItem>

                        <FormItem
                            style={{ float: 'center', marginTop:'-10px'}}>
                            <Button type="primary"  loading={this.state.buttonLoading} onConClick={() => this.submitDealed()}
                            style={{ width: '80%', height:'40px', fontSize:'1rem'}}>已处理</Button>
                        </FormItem> */}
                    {/* </Form> */}
                </div>

            </div>
        )
    }
}
const EventPushDeal = Form.create()(eventPushDeal);

export { EventPush, EventPushDeal }
// export default EventPush;
